'''
Created on 21 juil. 2010

@author: laurent
'''
import socket, os, cgi, time, gzip, StringIO

from BaseHTTPServer import BaseHTTPRequestHandler

class WebShellRequestHandler(BaseHTTPRequestHandler):
    def setup(self):
        self.connection = self.request
        self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
        self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
    def do_GET(self):
        path = os.path.basename(self.path)
        path = path.split('?', 1)
        if path[0] == 'u':
            try:
                p = cgi.parse_qs(path[1], True)
                sid = int(p['s'][0])
                k = p['k'][0]
                w = int(p['w'][0])
                h = int(p['h'][0])
                multiplex = self.server.webshell_multiplex            
                if multiplex.proc_keepalive(sid, w, h):
                    if k:
                        multiplex.proc_write(sid, k)
                    time.sleep(0.002)
                    content_type = 'text/xml'
                    content_data = '<?xml version="1.0" encoding="UTF-8"?>' + multiplex.proc_dump(sid)
                    content_gzip = True
                else:
                    self.send_error(400, 'Disconnected')
                    return
            except (KeyError, ValueError, IndexError):
                self.send_error(400, 'Invalid parameters')
                return
        else:
            files = self.server.webshell_files
            mime = self.server.webshell_mime
            f = path[0]
            if f not in files:
                if len(f) == 0:
                    f = 'webshell.html'
                else:
                    self.send_error(404, 'Not found')
                    return
            content_type = mime.get(
                os.path.splitext(f)[1].lower(), 'application/octet-stream')
            content_data = files[f]
            content_gzip = True

        self.send_response(200)
        self.send_header('Content-Type', content_type)
        if content_gzip and self.headers.get('Accept-Encoding','').find('gzip') != -1:
            zout = StringIO.StringIO()
            zfile = gzip.GzipFile(mode = 'wb', fileobj = zout)
            zfile.write(''.join(content_data))
            zfile.close()
            content_data = zout.getvalue()
            self.send_header('Content-Encoding', 'gzip')
        self.send_header('Content-Length', len(content_data))
        self.end_headers()
        self.wfile.write(content_data)
    def log_message(self,*p):
#        if self.server.log:
#            return BaseHTTPServer.BaseHTTPRequestHandler.log_message(self,*p)
        pass